<template>
    <div>
        <div style="margin-bottom: 10px; margin-top:10px" class="row end">
            <n-button @click="remoteBegin">设置远程零件</n-button>
        </div>
        <div style="margin-bottom: 10px">
            <div class="square" ref="refSquare"></div>
        </div>
        <div class="row center" style="margin-bottom: 10px">
            R: {{target && target.r}}, G: {{target && target.g}}, B: {{target && target.b}}
        </div>
        
        <div class="row gap15">
            <n-button class="grow" @click="remoteRead">读取</n-button>
            <n-button class="grow" type="primary" @click="remoteWatch">连续</n-button>
            <n-button class="grow" type="error" @click="remoteUnwatch">停止连续</n-button>
        </div>
    </div>
</template>

<style scoped>
.square {
    height: 40px ;
    margin-top: 10px;
}
</style>

<script lang="ts" setup>
import { ref, onMounted, Ref, watch } from 'vue'
import { conn } from '../../@beshell/conn-ts/Connection';
import { AppModel } from '../../../../model/AppModel';
import { BeColorDetector } from '../../../../model/parts/BeColorDetector';


const props = defineProps<{
    model: AppModel ,
    target: BeColorDetector ,
}>()

// declare var iro: any ;
// declare var $: any ;


let $square: any
const refSquare = ref(null) as unknown as Ref<HTMLElement>

onMounted (()=> {
    $square = $(refSquare.value)
})

function onTargetChagned(newTarget:BeColorDetector, oldTarget: BeColorDetector) {

    if(oldTarget) {

    }

    if(newTarget) {
        drawColor()
    }
}
watch(()=>props.target, onTargetChagned)
watch(()=>props.target.r, drawColor)
watch(()=>props.target.g, drawColor)
watch(()=>props.target.b, drawColor)


function drawColor() {
    if(props.target) {
        let color = '#' + (((props.target.r&255)<<16) | ((props.target.g&255)<<8) |  (props.target.b&255)).toString(16).padStart(6)
        $square.css('background-color', color)
    }
}

function remoteBegin() {
    if(!props.target) {
        return
    }
    if(!conn.isConnected){
        // ;(this as any).$Message.error("尚未链接到远程零件")
        // return
    }
    // let cable = props.target.serial()
    // if(!cable || !cable.isValid()) {
    //     ;(this as any).$Message.error("I2C串口线路尚未正确连接")
    //     return
    // }

    // cable.setup()
}

async function remoteRead() {
    if(!props.target) {
        return
    }
    await props.target.remoteRead()
    drawColor()
}

function remoteWatch() {
    if(!props.target) {
        return
    }
    props.target.remoteWatch()
}

function remoteUnwatch() {
    if(!props.target) {
        return
    }
    props.target.remoteUnwatch()
}
</script>